package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.LinearInterpolator;

import com.blankj.utilcode.util.ToastUtils;
import com.stark.beat.lib.core.BeatSettingManager;
import com.stark.beat.lib.core.BeatSoundType;
import com.stark.beat.lib.core.BeatSounder;
import com.stark.beat.lib.core.Beater;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityMetronomeBinding;
import flc.ast.dialog.BeatDialog;
import flc.ast.dialog.NoteDialog;
import flc.ast.dialog.SettingDialog;
import flc.ast.dialog.TimbreDialog;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.TimeUtil;

public class MetronomeActivity extends BaseAc<ActivityMetronomeBinding> {

    public static BeatSoundType sBeatSoundType;
    private BeatSettingManager mBeatSettingManager;
    private Beater mBeater;
    private BeatSounder mBeatSounder;
    private boolean hasPlay;
    private ObjectAnimator mRotaAnimator;
    private boolean hasSetTiming = false;//定时设置
    private int setTiming;//定时
    //调速设置
    private int mTimeInterval = 1;//时间间隔
    private int mAddSpeed = 50;//每次增加bpm
    private int mStartSpeed = 50;//开始速度
    private int mMaxSpeed = 200;//最大速度
    private int currentDuration;
    private Handler mTimeHandler;
    private Runnable runnableTime = new Runnable() {
        @Override
        public void run() {
            if (setTiming == 0) {
                stopSetTime();
                ToastUtils.showShort(R.string.timer_stop_name);
                return;
            }
            setTiming--;
            mTimeHandler.postDelayed(runnableTime, 1000);
        }
    };

    private Handler mHandler;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (currentDuration == 0) {
                stopTime();
                return;
            }
            currentDuration--;
            if (mBeatSettingManager.getBpm() + mAddSpeed >= mMaxSpeed) {
                mBeatSettingManager.setBpm(mMaxSpeed);
            } else {
                mBeatSettingManager.setBpm(mBeatSettingManager.getBpm() + mAddSpeed);
            }
            setBpmControl();
            mHandler.postDelayed(runnable, 1000 * 60);
        }
    };


    @Override
    protected int onCreate() {
        return R.layout.activity_metronome;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        mDataBinding.ivMetronomeBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mTimeHandler = new Handler();
        mHandler = new Handler();

        mBeatSettingManager = BeatSettingManager.getInstance();
        mBeater = Beater.getInstance();
        mBeatSounder = BeatSounder.getInstance();
        hasPlay = false;

        mDataBinding.beatView.setBeats(mBeatSettingManager.getBeats());


        mDataBinding.ivMetronomeNote.setOnClickListener(this);
        mDataBinding.ivMetronomeTimbre.setOnClickListener(this);
        mDataBinding.ivMetronomeBeat.setOnClickListener(this);
        mDataBinding.ivMetronomeSetting.setOnClickListener(this);
        mDataBinding.ivMetronomePlay.setOnClickListener(this);
        mDataBinding.ivMetronomeReduce.setOnClickListener(this);
        mDataBinding.ivMetronomeAdd.setOnClickListener(this);

    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivMetronomeNote:  //音符
                showNoteDialog();
                break;
            case R.id.ivMetronomeTimbre:  //音色
                showTimbreDialog();
                break;
            case R.id.ivMetronomeBeat:  //节拍
                showBeatDialog();
                break;
            case R.id.ivMetronomeSetting:  //设置
                showSettingDialog();
                break;
            case R.id.ivMetronomeReduce:  // 减
                mBeatSettingManager.setBpm(mBeatSettingManager.getBpm() - 1);
                setBpmControl();
                break;
            case R.id.ivMetronomePlay:  // 播放
                if (hasPlay) {
                    hasPlay = false;
                    mDataBinding.ivMetronomePlay.setImageResource(R.drawable.kaishi1);
                    mBeater.stop();
                    mRotaAnimator.cancel();
                } else {
                    hasPlay = true;
                    mDataBinding.ivMetronomePlay.setImageResource(R.drawable.zanting1);
                    mBeater.start();
                    mRotaAnimator.start();
                }
                break;
            case R.id.ivMetronomeAdd:  // 加
                mBeatSettingManager.setBpm(mBeatSettingManager.getBpm() + 1);
                setBpmControl();
                break;
        }
    }

    @Override
    protected void initData() {
        initAnimator();
        setBpmControl();
        mBeatSettingManager.setBeatSoundType(sBeatSoundType);
        //给设置管理器设置
        mBeatSettingManager.addListener(mBeater);
        mBeatSettingManager.addListener(mBeatSounder);
        mBeatSettingManager.addListener(mDataBinding.beatView.getBeatSetListener());
        //给节拍器设置监听器
        mBeater.addListener(new Beater.IListener() {
            @Override
            public void onBeatCome(int beatIdx) {
                mDataBinding.beatView.setSelBeatIdx(beatIdx);
                if (mBeatSettingManager.isSoundByHuman()) {
                    mBeatSounder.playSound(beatIdx);
                } else {
                    mBeatSounder.playSound(mDataBinding.beatView.getSelBeatHeightIdx());
                }
            }
        });
    }

    private void showNoteDialog() {
        NoteDialog noteDialog = new NoteDialog(mContext);
        noteDialog.setListener(new NoteDialog.IListener() {
            @Override
            public void onClickConfirm(int note) {
                mBeatSettingManager.setNotes(note);
            }
        });
        noteDialog.setNote(mBeatSettingManager.getNotes());
        noteDialog.show();
    }

    private void showTimbreDialog() {
        TimbreDialog timbreDialog = new TimbreDialog(mContext);
        timbreDialog.setListener(new TimbreDialog.IListener() {
            @Override
            public void onClickConfirm(BeatSoundType beatSoundType) {
                mBeatSettingManager.setBeatSoundType(beatSoundType);
            }
        });
        timbreDialog.setTimbre(mBeatSettingManager.getBeatSoundType());
        timbreDialog.show();
    }

    private void showBeatDialog() {
        BeatDialog beatDialog = new BeatDialog(mContext);
        beatDialog.setListener(new BeatDialog.IListener() {
            @Override
            public void onClickConfirm(int beat) {
                mBeatSettingManager.setBeats(beat);
            }
        });
        beatDialog.setBeat(mBeatSettingManager.getBeats());
        beatDialog.show();
    }

    private void showSettingDialog() {
        SettingDialog settingDialog = new SettingDialog(mContext);
        settingDialog.setListener(new SettingDialog.IListener() {
            @Override
            public void onClickConfirm(boolean hasOpenFlash, boolean hasOpenVibrate, boolean hasSetTime, int timing, int timeInterval, int addSpeed, int startSpeed, int maxSpeed) {
                mBeatSettingManager.setOpenFlash(hasOpenFlash);
                mBeatSettingManager.setOpenVibrate(hasOpenVibrate);
                hasSetTiming = hasSetTime;
                if (hasSetTiming) {
                    setTiming = timing;
                    startSetTime();
                }
                mTimeInterval = timeInterval;
                currentDuration = mTimeInterval;
                mAddSpeed = addSpeed;
                mStartSpeed = startSpeed;
                mMaxSpeed = maxSpeed;
                mBeatSettingManager.setBpm(mStartSpeed);
                setBpmControl();
                startTime();
            }
        });
        settingDialog.setFlashLamp(mBeatSettingManager.isOpenFlash());
        settingDialog.setVibration(mBeatSettingManager.isOpenVibrate());
        settingDialog.setTime(hasSetTiming);
        settingDialog.setTimeInterval(mTimeInterval);
        settingDialog.setAddSpeed(mAddSpeed);
        settingDialog.setStartSpeed(mStartSpeed);
        settingDialog.setMaxSpeed(mMaxSpeed);
        settingDialog.show();
    }

    private void setBpmControl() {
        mDataBinding.tvMetronomeBpmCount.setText(mBeatSettingManager.getBpm() + "");
    }

    private void initAnimator() {
        mRotaAnimator = ObjectAnimator.ofFloat(mDataBinding.rlMetronomeIcon, "rotation", 0f, 360f);
//        mDataBinding.ivMetronomePoint.setPivotX(-180);
//        mDataBinding.ivMetronomePoint.setPivotY(235);
        mRotaAnimator.setRepeatCount(ValueAnimator.INFINITE);
        mRotaAnimator.setInterpolator(new LinearInterpolator());//插值器实现匀速旋转
        mRotaAnimator.setDuration(3000);//时间
    }

    private void startSetTime() {
        mTimeHandler.post(runnableTime);
    }

    private void stopSetTime() {
        mTimeHandler.removeCallbacks(runnableTime);
    }

    private void startTime() {
        mHandler.postDelayed(runnable,60*1000);
    }

    private void stopTime() {
        mHandler.removeCallbacks(runnable);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBeater.stop();
        mBeatSettingManager.delListener(mBeater);
        mBeatSettingManager.delListener(mBeatSounder);
        mBeatSounder.release();
        mRotaAnimator.cancel();
    }
}